package com.dd.cloud.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义访问对象工具类
 * <p>
 * 获取对象的IP地址等信息
 *
 * @author X-rapido
 */
public class IPUtil {


    /**
     * 获取用户真实IP地址，不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * 参考文章： http://developer.51cto.com/art/201111/305181.htm
     * <p>
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值，究竟哪个才是真正的用户端的真实IP呢？
     * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。
     * <p>
     * 如：X-Forwarded-For：192.168.1.110, 192.168.1.120, 192.168.1.130,
     * 192.168.1.100
     * <p>
     * 用户真实IP为： 192.168.1.110
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        /**
         * 获取客户端ip，客户端可能经过代理，也可能没经过代理
         */
        String ip = request.getHeader("x-forwarded-for");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        //如果没取到ip，返回""
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = "";
        }

        return ip;

    }

    /**
     * 获取ip归属地 可能响应会很慢
     *
     * @param ip
     * @return
     */
    public static IpAddr getIpAddr(String ip) {
        try {
            String res = HttpRequestUtils.get("https://searchplugin.csdn.net/api/v1/ip/get?ip=" + ip);
            JSONObject obj = JSON.parseObject(res);
            if (obj.getString("code").equals("200")) {
                String addr = obj.getJSONObject("data").getString("address");
                String[] splits = addr.split(" ");
                IpAddr ipAddr = new IpAddr();
                ipAddr.setGj(splits[0]);
                if (ipAddr.getGj().equals("中国")) {
                    ipAddr.setInfo1(splits[1]);
                    ipAddr.setInfo2(splits[2]);
                    ipAddr.setIsp(splits[3]);
                    if (splits.length == 5) {
                        ipAddr.setInfo3(splits[3]);
                        ipAddr.setIsp(splits[4]);
                    }
                }
                ipAddr.setDetail(addr);
                return ipAddr;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            String res = HttpRequestUtils.get("https://whois.pconline.com.cn/ipJson.jsp?ip=" + ip + "&json=true");
            JSONObject obj = JSON.parseObject(res);
            if (obj != null) {
                String addr = obj.getString("addr");
                String[] splits = addr.split(" ");
                IpAddr ipAddr = new IpAddr();
                ipAddr.setInfo1(obj.getString("pro"));
                ipAddr.setInfo2(obj.getString("city"));
                if (splits.length == 2) {
                    ipAddr.setIsp(splits[1]);
                }
                ipAddr.setDetail(addr);
                return ipAddr;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            String res = HttpRequestUtils.get("https://api.vore.top/api/IPdata?ip=" + ip);
            JSONObject obj = JSON.parseObject(res);
            if (obj.getString("code").equals("200")) {
                return obj.getObject("ipdata", IpAddr.class);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取端口
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();//返回请求行中的资源名称
        String url = request.getRequestURL().toString();//获得客户端发送请求的完整url
        String ip = request.getRemoteAddr();//返回发出请求的IP地址
        String params = request.getQueryString();//返回请求行中的参数部分
        String host = request.getRemoteHost();//返回发出请求的客户机的主机名
        int port = request.getRemotePort();//返回发出请求的客户机的端口号。
        System.out.println(ip);
        System.out.println(url);
        System.out.println(uri);
        System.out.println(params);
        System.out.println(host);
        System.out.println(port);
    }

    /**
     * ip归属地
     */
    @Data
    public static class IpAddr {
        /**
         * 国家
         */
        private String gj;
        /**
         * 省份
         */
        private String info1;
        /**
         * 城市
         */
        private String info2;
        /**
         * 区县
         */
        private String info3;
        /**
         * 网络运营商
         */
        private String isp;
        /**
         * 详细信息
         */
        private String detail;
    }
}
